package com.atguigu.spzx.manager.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.spzx.common.util.AuthContextUtil;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: LoginAuthInterceptor
 * @Package: com.atguigu.spzx.manager.interceptor
 * @Description 创建拦截器校验用户登陆信息是否过期
 * @Author 孤妤
 * @Date: 2023/12/2 16:54
 */
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求方式
        String method = request.getMethod();
        // 判断是否是预检请求
        if ("OPTIONS".equals(method)){
            return true;
        }
        // 获取请求头中的token
        String token = request.getHeader("token");
        // 判断是否为空
        if (StrUtil.isEmpty(token)){
            noLoginResponse(response);
            return false;
        }
        // 根据token获取用户信息
        String sysUserStr = redisTemplate.opsForValue().get("user:login:" + token);
        if (StrUtil.isEmpty(sysUserStr)){
            noLoginResponse(response);
            return false;
        }
        // 将用户信息保存到当前线程中
        AuthContextUtil.set(JSONObject.parseObject(sysUserStr, SysUser.class));
        redisTemplate.opsForValue().set("user:login:"+token,sysUserStr,2, TimeUnit.HOURS);
        return true;
    }

    private void noLoginResponse(HttpServletResponse response) {
        Result result = Result.build(null, ResultCodeEnum.NO_AUTH);
        response.setContentType("text/html;charset=utf-8");
        try {
            PrintWriter writer = response.getWriter();
            writer.print(JSONObject.toJSONString(result));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.remove();
    }
}
